<template>
  <div class="route-container" style="overflow-y: hidden!important;height: 100vh!important;">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="left">
        <el-button type="primary" @click="handleAddRoute" :icon="Plus">新增线路</el-button>
        <el-button type="success" @click="handleAddSpot" :icon="Plus">新增景点</el-button>
      </div>
      <el-input
        v-model="searchKey"
        placeholder="搜索线路名称/景点名称"
        class="search-input"
        :prefix-icon="Search"
        clearable
      />
    </div>

    <!-- 线路和景点列表 -->
    <el-card class="table-card" :body-style="{ padding: '0px' }" v-loading="loading">
      <el-tabs v-model="activeTab" class="custom-tabs" @tab-change="handleTabChange">
        <el-tab-pane label="旅游线路" name="route">
          <div class="table-container">
            <div v-if="!routeList.length" style="text-align: center; padding: 20px;">
              暂无数据
            </div>
            <template v-else>
              <!-- 添加数据统计 -->
              <div style="padding: 10px; color: #666; font-size: 12px;">
                总数据: {{ routeList.length }} | 
                过滤后: {{ filteredRouteList.length }} | 
                当前页: {{ paginatedRouteList.length }}
              </div>

              <el-table 
                :data="paginatedRouteList" 
                style="width: 100%"
                :header-cell-style="{ background: '#f5f7fa' }"
                border>
                <el-table-column prop="routeId" label="线路ID" width="100" align="center" />
                <el-table-column prop="routeName" label="线路名称" min-width="180" align="center" />
                <el-table-column prop="price" label="成本价格" width="120" align="center">
                  <template #default="scope">
                    ¥{{ scope.row.price }}
                  </template>
                </el-table-column>
                <el-table-column prop="routeDescription" label="线路描述" min-width="200" align="center" show-overflow-tooltip />
                <el-table-column label="包含景点" min-width="200" align="center">
                  <template #default="scope">
                    <el-tag 
                      v-for="spot in scope.row.spots" 
                      :key="spot.spotId"
                      class="spot-tag"
                      effect="plain">
                      {{ spot.spotName }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right" align="center">
                  <template #default="scope">
                    <el-button type="primary" link @click="handleViewRoute(scope.row)">
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 添加分页器 -->
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="routeCurrentPage"
                  v-model:page-size="routePageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="filteredRouteList.length"
                  background
                />
              </div>
            </template>
          </div>
        </el-tab-pane>

        <el-tab-pane label="景点信息" name="spot">
          <div class="table-container">
            <div v-if="!spotList.length" style="text-align: center; padding: 20px;">
              暂无数据
            </div>
            <template v-else>
              <!-- 添加数据统计 -->
              <div style="padding: 10px; color: #666; font-size: 12px;">
                总数据: {{ spotList.length }} | 
                过滤后: {{ filteredSpotList.length }} | 
                当前页: {{ paginatedSpotList.length }}
              </div>

              <el-table 
                :data="paginatedSpotList" 
                style="width: 100%"
                :header-cell-style="{ background: '#f5f7fa' }"
                border>
                <el-table-column prop="spotId" label="景点ID" width="100" align="center" />
                <el-table-column prop="spotName" label="景点名称" min-width="180" align="center" />
                <el-table-column prop="spotDescription" label="景点描述" min-width="300" align="center" show-overflow-tooltip />
              </el-table>

              <!-- 添加分页器 -->
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="spotCurrentPage"
                  v-model:page-size="spotPageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="filteredSpotList.length"
                  background
                />
              </div>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增/查看线路对话框 -->
    <el-dialog
      v-model="routeDialogVisible"
      :title="routeFormType === 'add' ? '新增线路' : '线路详情'"
      width="700px"
      :close-on-click-modal="false"
      destroy-on-close>
      <el-form
        ref="routeFormRef"
        :model="routeForm"
        :rules="routeRules"
        label-width="100px"
        class="custom-form">
        <el-form-item label="线路名称" prop="routeName">
          <el-input 
            v-model="routeForm.routeName" 
            placeholder="请输入线路名称"
            :disabled="routeFormType === 'view'" />
        </el-form-item>
        <el-form-item label="成本价格" prop="price">
          <el-input-number 
            v-model="routeForm.price" 
            :min="0"
            :precision="2"
            :step="100"
            class="full-width"
            :disabled="routeFormType === 'view'" />
        </el-form-item>
        <el-form-item label="线路描述" prop="routeDescription">
          <el-input 
            v-model="routeForm.routeDescription" 
            type="textarea" 
            rows="3"
            placeholder="请输入线路描述"
            :disabled="routeFormType === 'view'" />
        </el-form-item>
        <el-form-item label="选择景点" prop="spotsIds">
          <el-select
            v-model="routeForm.spotsIds"
            multiple
            placeholder="请选择包含的景点"
            class="full-width"
            :disabled="routeFormType === 'view'">
            <el-option
              v-for="spot in spotList"
              :key="spot.spotId"
              :label="spot.spotName"
              :value="spot.spotId">
              <div class="spot-option">
                <span>{{ spot.spotName }}</span>
                <el-tooltip 
                  :content="spot.spotDescription" 
                  placement="right"
                  :show-after="500">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="routeDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="routeFormType === 'add'"
            type="primary" 
            @click="submitRouteForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增景点对话框 -->
    <el-dialog
      v-model="spotDialogVisible"
      title="新增景点"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close>
      <el-form
        ref="spotFormRef"
        :model="spotForm"
        :rules="spotRules"
        label-width="100px"
        class="custom-form">
        <el-form-item label="景点名称" prop="spotName">
          <el-input v-model="spotForm.spotName" placeholder="请输入景点名称" />
        </el-form-item>
        <el-form-item label="景点描述" prop="spotDescription">
          <el-input 
            v-model="spotForm.spotDescription" 
            type="textarea" 
            rows="3"
            placeholder="请输入景点描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="spotDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSpotForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { Plus, Search, InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { routeApi } from '@/api/modules/route'
import type { Route, Spot } from '@/api/modules/route'

// 数据定义
const activeTab = ref('route')
const searchKey = ref('')
const routeList = ref<Route[]>([])
const spotList = ref<Spot[]>([])
const routeDialogVisible = ref(false)
const spotDialogVisible = ref(false)
const routeFormType = ref<'add' | 'view'>('add')
const routeFormRef = ref<FormInstance>()
const spotFormRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const routeForm = ref({
  routeId: undefined,
  routeName: '',
  price: 0,
  routeDescription: '',
  spotsIds: [] as number[]
})

const spotForm = ref({
  spotName: '',
  spotDescription: ''
})

// 表单校验规则
const routeRules = ref<FormRules>({
  routeName: [
    { required: true, message: '请输入线路名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 字符', trigger: 'blur' }
  ],
  price: [{ required: true, message: '请输入成本价格', trigger: 'blur' }],
  routeDescription: [{ required: true, message: '请输入线路描述', trigger: 'blur' }],
  spotsIds: [{ required: true, message: '请选择至少一个景点', trigger: 'change' }]
})

const spotRules = ref<FormRules>({
  spotName: [
    { required: true, message: '请输入景点名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  spotDescription: [{ required: true, message: '请输入景点描述', trigger: 'blur' }]
})

// 搜索过滤
const filteredRouteList = computed(() => {
  if (!searchKey.value) return routeList.value
  return routeList.value.filter(item => 
    item.routeName.includes(searchKey.value)
  )
})

const filteredSpotList = computed(() => {
  if (!searchKey.value) return spotList.value
  return spotList.value.filter(item => 
    item.spotName.includes(searchKey.value)
  )
})

// 添加分页相关的 ref
const routeCurrentPage = ref(1)
const routePageSize = ref(10)
const spotCurrentPage = ref(1) 
const spotPageSize = ref(10)

// 添加分页后的计算属性
const paginatedRouteList = computed(() => {
  const list = filteredRouteList.value
  if (!list || list.length === 0) return []
  
  const startIndex = (routeCurrentPage.value - 1) * routePageSize.value
  const endIndex = startIndex + routePageSize.value
  return list.slice(startIndex, endIndex)
})

const paginatedSpotList = computed(() => {
  const list = filteredSpotList.value
  if (!list || list.length === 0) return []
  
  const startIndex = (spotCurrentPage.value - 1) * spotPageSize.value
  const endIndex = startIndex + spotPageSize.value
  return list.slice(startIndex, endIndex)
})

// 获取数据
const fetchData = async () => {
  try {
    const [routeRes, spotRes] = await Promise.all([
      routeApi.getAllRoutes(),
      routeApi.getAllSpots()
    ])
    
    // 确保返回的数据存在且是数组
    routeList.value = routeRes??[]
    spotList.value = spotRes??[]
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
    // 确保发生错误时设置为空数组
    routeList.value = []
    spotList.value = []
  }
}

// 新增线路
const handleAddRoute = () => {
  routeFormType.value = 'add'
  routeForm.value = {
    routeId: undefined,
    routeName: '',
    price: 0,
    routeDescription: '',
    spotsIds: []
  }
  routeDialogVisible.value = true
}

// 查看线路详情
const handleViewRoute = (row: any) => {
  routeFormType.value = 'view'
  routeForm.value = {
    ...row,
    spotsIds: row.spots.map((spot: any) => spot.spotId)
  }
  routeDialogVisible.value = true
}

// 新增景点
const handleAddSpot = () => {
  spotForm.value = {
    spotName: '',
    spotDescription: ''
  }
  spotDialogVisible.value = true
}

// 提交线路表单
const submitRouteForm = async () => {
  if (!routeFormRef.value) return
  
  await routeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        ElMessage.success('添加成功')
        routeDialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error('添加失败:', error)
        ElMessage.error('添加失败')
      }
    }
  })
}

// 提交景点表单
const submitSpotForm = async () => {
  if (!spotFormRef.value) return
  
  await spotFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await routeApi.addSpot(spotForm.value)
        ElMessage.success('添加成功')
        spotDialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error('添加失败:', error)
        ElMessage.error('添加失败')
      }
    }
  })
}

const handleTabChange = async () => {
  loading.value = true
  await nextTick()
  setTimeout(() => {
    loading.value = false
  }, 300)
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.route-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
  padding-bottom: 120px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  padding: 0 20px;
}

.table-container {
  padding: 0;
}

.custom-tabs {
  padding: 20px 20px 0;
}

.custom-form {
  padding: 20px;
}

.full-width {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
}

.spot-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.spot-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 10px;
}

:deep(.el-table) {
  margin: 20px 0;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__cell) {
  text-align: center;
  .cell {
    white-space: nowrap;
  }
}

:deep(.el-table__inner-wrapper) {
  padding: 0 !important;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 24px;
  margin-bottom: 80px;
  background-color: #fff;
  border-top: 1px solid #EBEEF5;
}

:deep(.el-pagination) {
  padding: 0;
  font-weight: normal;
}

:deep(.el-pagination .el-pagination__total) {
  font-weight: normal;
}
</style> 